package com.example.tests;

import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.EditMoviePage;
import com.example.pages.HomePage;
import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.MovieProfilePage;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import ru.esteru.selenium.factory.WebDriverFactory;

public class EditFilm {
	private static WebDriver driver;
	private static WebDriverWait wait;
	private static String baseUrl;

	@BeforeClass
	public static void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		wait = new WebDriverWait(driver, 10);
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	public LoginPage loginPage;
	public InternalPage somePage;
	String movieNumber = "movie_16";
	private EditMoviePage editMoviePage;
	private HomePage homePage;
	private MovieProfilePage movieProfilePage;

	@Test
	public void testEditMovie() {
		goToMainPage();
		loginAs("admin", "admin");
		editMovie(movieNumber, "183");
		logOut();

	}

	private void editMovie(String movieNumber, String minutes) {
		homePage.movie16Link.click();
		movieProfilePage.editLink.click();
		editMoviePage.durationField.clear();
		editMoviePage.durationField.sendKeys(minutes);
		editMoviePage.saveButton.click();
		assertTrue("Film duration is saved",
				movieProfilePage.isDurationFilmSaved(minutes));

		movieProfilePage.seenLink.click();
		movieProfilePage.unseenLink.click();
		homePage.menuHomeLink.click();
		assertTrue("Home page doesn't opens", homePage.isHomePageOpened());
	}

	private void loginAs(String userName, String password) {

		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(userName);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
	}

	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
		editMoviePage = PageFactory.initElements(driver, EditMoviePage.class);
		homePage = PageFactory.initElements(driver, HomePage.class);
		movieProfilePage = PageFactory.initElements(driver,
				MovieProfilePage.class);
	}

	private void logOut() {
		somePage.menuLogoutLink.click();
		wait.until(alertIsPresent()).accept();
	}

}
